import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Image, TouchableOpacity, StyleSheet, RefreshControl, Modal, TextInput, ToastAndroid, ScrollView } from 'react-native';
import api from '../services/api';
import CustomHeader from '../components/CustomHeader';

const FeedScreen = ({ navigation }) => {
  const [feeds, setFeeds] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [newPostContent, setNewPostContent] = useState('');
  const [mediaUri, setMediaUri] = useState('');
  const [postType, setPostType] = useState('text'); // text, image, video
  const [commentInputs, setCommentInputs] = useState({}); // 用于存储每个动态的评论输入
  const [comments, setComments] = useState({}); // 用于存储每个动态的评论列表

  useEffect(() => {
    loadFeeds();
  }, []);

  const loadFeeds = async () => {
    try {
      const response = await api.getFeeds();
      if (response.success) {
        // 初始化每个动态的评论输入状态
        const initialCommentInputs = {};
        response.data.forEach(feed => {
          initialCommentInputs[feed.id] = '';
        });
        setCommentInputs(initialCommentInputs);
        
        setFeeds(response.data);
        
        // 加载每个动态的评论
        response.data.forEach(feed => {
          loadComments(feed.id);
        });
      }
    } catch (error) {
      console.error('获取动态失败:', error);
      ToastAndroid.show('获取动态失败', ToastAndroid.SHORT);
    }
  };

  const loadComments = async (postId) => {
    try {
      const response = await api.getComments(postId);
      if (response.success) {
        setComments(prev => ({
          ...prev,
          [postId]: response.data
        }));
      }
    } catch (error) {
      console.error('获取评论失败:', error);
      // 不显示错误提示，因为可能没有评论
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    try {
      const response = await api.getFeeds();
      if (response.success) {
        // 初始化每个动态的评论输入状态
        const initialCommentInputs = {};
        response.data.forEach(feed => {
          initialCommentInputs[feed.id] = '';
        });
        setCommentInputs(initialCommentInputs);
        
        setFeeds(response.data);
        
        // 加载每个动态的评论
        response.data.forEach(feed => {
          loadComments(feed.id);
        });
      }
    } catch (error) {
      console.error('刷新动态失败:', error);
      ToastAndroid.show('刷新动态失败', ToastAndroid.SHORT);
    } finally {
      setRefreshing(false);
    }
  };

  const handlePost = async () => {
    if (newPostContent.trim() === '' && !mediaUri) {
      ToastAndroid.show('请输入内容或选择媒体', ToastAndroid.SHORT);
      return;
    }
    
    try {
      const feedData = {
        content: mediaUri ? newPostContent : newPostContent,
        type: mediaUri ? postType : 'text',
        mediaUrl: mediaUri || null,
        thumbnailUrl: postType === 'video' && mediaUri ? 'https://picsum.photos/400/300?random=3' : null
      };

      const response = await api.createFeed(feedData);
      if (response.success) {
        ToastAndroid.show('发布成功', ToastAndroid.SHORT);
        setNewPostContent('');
        setMediaUri('');
        setPostType('text');
        setModalVisible(false);
        // 重新加载动态
        loadFeeds();
      } else {
        ToastAndroid.show(response.message || '发布失败', ToastAndroid.SHORT);
      }
    } catch (error) {
      console.error('发布动态失败:', error);
      ToastAndroid.show('发布动态失败', ToastAndroid.SHORT);
    }
  };

  const selectMedia = (type) => {
    setPostType(type);
    // 模拟选择媒体
    if (type === 'image') {
      setMediaUri('https://picsum.photos/400/300?random=' + Math.floor(Math.random() * 100));
    } else if (type === 'video') {
      setMediaUri('https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4');
    }
  };

  const removeMedia = () => {
    setMediaUri('');
    setPostType('text');
  };

  const handleLike = async (postId) => {
    try {
      const response = await api.togglePostLike(postId);
      if (response.success) {
        // 更新动态的点赞状态
        setFeeds(prevFeeds => 
          prevFeeds.map(feed => 
            feed.id === postId 
              ? { ...feed, likeInfo: response.data } 
              : feed
          )
        );
      } else {
        ToastAndroid.show(response.message || '操作失败', ToastAndroid.SHORT);
      }
    } catch (error) {
      console.error('点赞失败:', error);
      ToastAndroid.show('操作失败', ToastAndroid.SHORT);
    }
  };

  const handleAddComment = async (postId) => {
    const content = commentInputs[postId];
    if (!content || content.trim() === '') {
      ToastAndroid.show('请输入评论内容', ToastAndroid.SHORT);
      return;
    }

    try {
      const response = await api.addComment(postId, content);
      if (response.success) {
        // 清空输入框
        setCommentInputs(prev => ({
          ...prev,
          [postId]: ''
        }));
        
        // 重新加载评论
        loadComments(postId);
        
        ToastAndroid.show('评论成功', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show(response.message || '评论失败', ToastAndroid.SHORT);
      }
    } catch (error) {
      console.error('评论失败:', error);
      ToastAndroid.show('评论失败', ToastAndroid.SHORT);
    }
  };

  const renderFeed = ({ item: feed }) => {
    const feedComments = comments[feed.id] || [];
    const likeInfo = feed.likeInfo || { liked: false, count: 0 };
    
    return (
      <View style={styles.feedItem}>
        {/* 用户信息 */}
        <View style={styles.feedHeader}>
          <Image 
            source={{ uri: feed.user?.avatar || 'https://via.placeholder.com/50' }} 
            style={styles.userAvatar}
          />
          <View style={styles.userInfo}>
            <Text style={styles.userName}>{feed.user?.name || '匿名用户'}</Text>
            <Text style={styles.feedTime}>{new Date(feed.createdAt).toLocaleString()}</Text>
          </View>
        </View>

        {/* 动态内容 */}
        <View style={styles.feedContent}>
          {feed.type === 'text' && (
            <Text style={styles.textContent}>{feed.content}</Text>
          )}

          {feed.type === 'image' && (
            <>
              <Image source={{ uri: feed.mediaUrl }} style={styles.imageContent} />
              {feed.content && <Text style={styles.caption}>{feed.content}</Text>}
            </>
          )}

          {feed.type === 'video' && (
            <>
              <TouchableOpacity style={styles.videoContainer}>
                <Image source={{ uri: feed.thumbnailUrl }} style={styles.videoThumbnail} />
                <View style={styles.playButton}>
                  <Text style={styles.playButtonText}>▶</Text>
                </View>
              </TouchableOpacity>
              {feed.content && <Text style={styles.caption}>{feed.content}</Text>}
            </>
          )}
        </View>

        {/* 互动区域 */}
        <View style={styles.feedActions}>
          <TouchableOpacity 
            style={styles.actionButton} 
            onPress={() => handleLike(feed.id)}
          >
            <Text style={[styles.actionText, likeInfo.liked && styles.likedText]}>
              👍 {likeInfo.count}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.actionButton}>
            <Text style={styles.actionText}>💬 {feedComments.length}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.actionButton}>
            <Text style={styles.actionText}>↗️ 分享</Text>
          </TouchableOpacity>
        </View>

        {/* 评论区域 */}
        <View style={styles.commentsSection}>
          {/* 显示前2条评论 */}
          {feedComments.slice(0, 2).map(comment => (
            <View key={comment.id} style={styles.commentItem}>
              <Text style={styles.commentUser}>{comment.user?.name || '匿名用户'}:</Text>
              <Text style={styles.commentContent}>{comment.content}</Text>
            </View>
          ))}

          {/* 评论输入框 */}
          <View style={styles.commentInputContainer}>
            <TextInput
              style={styles.commentInput}
              placeholder="添加评论..."
              value={commentInputs[feed.id] || ''}
              onChangeText={text => 
                setCommentInputs(prev => ({
                  ...prev,
                  [feed.id]: text
                }))
              }
              onSubmitEditing={() => handleAddComment(feed.id)}
            />
            <TouchableOpacity 
              style={styles.commentSendButton}
              onPress={() => handleAddComment(feed.id)}
            >
              <Text style={styles.commentSendButtonText}>发送</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <CustomHeader title="动态" showMenuButton={true} />
      
      <FlatList
        data={feeds}
        renderItem={renderFeed}
        keyExtractor={(item) => item.id.toString()}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      />

      <TouchableOpacity style={styles.fab} onPress={() => setModalVisible(true)}>
        <Text style={styles.fabText}>+</Text>
      </TouchableOpacity>

      {/* 发布动态模态框 */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(false);
          setNewPostContent('');
          setMediaUri('');
          setPostType('text');
        }}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <TouchableOpacity onPress={() => {
                setModalVisible(false);
                setNewPostContent('');
                setMediaUri('');
                setPostType('text');
              }}>
                <Text style={styles.cancelButton}>取消</Text>
              </TouchableOpacity>
              <Text style={styles.modalTitle}>发布动态</Text>
              <TouchableOpacity onPress={handlePost}>
                <Text style={[styles.postButton, styles.modalPostButton]}>发布</Text>
              </TouchableOpacity>
            </View>
            
            <View style={styles.mediaPreviewContainer}>
              {mediaUri ? (
                <View style={styles.mediaPreview}>
                  {postType === 'image' ? (
                    <Image source={{ uri: mediaUri }} style={styles.previewImage} />
                  ) : (
                    <View style={styles.videoPreview}>
                      <Text style={styles.videoPreviewText}>视频预览</Text>
                    </View>
                  )}
                  <TouchableOpacity style={styles.removeMediaButton} onPress={removeMedia}>
                    <Text style={styles.removeMediaText}>✕</Text>
                  </TouchableOpacity>
                </View>
              ) : (
                <View style={styles.mediaButtons}>
                  <TouchableOpacity style={styles.mediaButton} onPress={() => selectMedia('image')}>
                    <Text style={styles.mediaButtonText}>📷 照片</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.mediaButton} onPress={() => selectMedia('video')}>
                    <Text style={styles.mediaButtonText}>📹 视频</Text>
                  </TouchableOpacity>
                </View>
              )}
            </View>
            
            <TextInput
              style={styles.postInput}
              placeholder="分享新鲜事..."
              multiline
              value={newPostContent}
              onChangeText={setNewPostContent}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  feedItem: {
    backgroundColor: 'white',
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 8,
    elevation: 2,
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  feedHeader: {
    flexDirection: 'row',
    padding: 16,
    alignItems: 'center',
  },
  userAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 12,
  },
  userInfo: {
    flex: 1,
  },
  userName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  feedTime: {
    fontSize: 12,
    color: 'gray',
    marginTop: 2,
  },
  feedContent: {
    paddingHorizontal: 16,
    paddingBottom: 16,
  },
  textContent: {
    fontSize: 16,
    lineHeight: 22,
  },
  imageContent: {
    width: '100%',
    height: 200,
    resizeMode: 'cover',
    borderRadius: 8,
    marginVertical: 8,
  },
  videoContainer: {
    position: 'relative',
    marginVertical: 8,
  },
  videoThumbnail: {
    width: '100%',
    height: 200,
    resizeMode: 'cover',
    borderRadius: 8,
  },
  playButton: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{ translateX: -20 }, { translateY: -20 }],
    backgroundColor: 'rgba(0,0,0,0.7)',
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  playButtonText: {
    color: 'white',
    fontSize: 18,
  },
  caption: {
    marginTop: 8,
    fontSize: 14,
    color: '#333',
  },
  feedActions: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    paddingVertical: 12,
  },
  actionButton: {
    flex: 1,
    alignItems: 'center',
  },
  actionText: {
    fontSize: 16,
    color: '#666',
  },
  likedText: {
    color: '#2196F3',
  },
  commentsSection: {
    paddingHorizontal: 16,
    paddingBottom: 16,
    backgroundColor: '#f9f9f9',
  },
  commentItem: {
    flexDirection: 'row',
    marginBottom: 8,
  },
  commentUser: {
    fontWeight: 'bold',
    marginRight: 8,
  },
  commentContent: {
    flex: 1,
  },
  commentInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  commentInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 16,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 14,
  },
  commentSendButton: {
    marginLeft: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  commentSendButtonText: {
    color: '#2196F3',
    fontWeight: 'bold',
  },
  fab: {
    position: 'absolute',
    right: 20,
    bottom: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: '#2196F3',
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 8,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
  },
  fabText: {
    fontSize: 24,
    color: 'white',
    fontWeight: 'bold',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  modalContent: {
    backgroundColor: 'white',
    width: '90%',
    borderRadius: 10,
    overflow: 'hidden',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  modalPostButton: {
    color: '#2196F3',
  },
  cancelButton: {
    color: 'gray',
  },
  mediaPreviewContainer: {
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  mediaPreview: {
    position: 'relative',
  },
  previewImage: {
    width: '100%',
    height: 200,
    resizeMode: 'cover',
    borderRadius: 8,
  },
  videoPreview: {
    width: '100%',
    height: 200,
    backgroundColor: '#333',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  videoPreviewText: {
    color: 'white',
    fontSize: 16,
  },
  removeMediaButton: {
    position: 'absolute',
    top: 10,
    right: 10,
    backgroundColor: 'rgba(0,0,0,0.5)',
    width: 30,
    height: 30,
    borderRadius: 15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  removeMediaText: {
    color: 'white',
    fontSize: 18,
  },
  mediaButtons: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  mediaButton: {
    padding: 15,
    backgroundColor: '#f0f0f0',
    borderRadius: 8,
  },
  mediaButtonText: {
    fontSize: 16,
  },
  postInput: {
    minHeight: 150,
    padding: 15,
    fontSize: 16,
    textAlignVertical: 'top',
  },
});

export default FeedScreen;